﻿using System;
using System.Configuration;
using ErrorDumper.Filtering;

namespace ErrorDumper.Configuration {
    public class FilterElementCollection : ConfigurationElementCollection, IExceptionFilter {
        
        public FilterElementCollection() {
            AddElementName = "filter";
        }

        [ConfigurationProperty("defaultMode", IsRequired = false, DefaultValue = ExceptionHandlingLevel.WriteExtendedDump)]
        public ExceptionHandlingLevel DefaultHandlingLevel {
            get { return (ExceptionHandlingLevel)this["defaultMode"]; }
            set { this["defaultMode"] = value; }
        }

        protected override ConfigurationElement CreateNewElement() {
            return new FilterElement();
        }

        protected override object GetElementKey(ConfigurationElement element) {
            return ((FilterElement)element).Name;
        }

        private ExceptionHandlingLevel HandleExceptionCore(ExceptionPropertyCollection properties) {
            var level = DefaultHandlingLevel;
            if (level == ExceptionHandlingLevel.Ignore)
                return ExceptionHandlingLevel.Ignore;

            if (properties != null)
                foreach (FilterElement entry in this)
                    if (entry.IsMatch(properties) &&
                        !ExceptionFilters.Resolve(ref level, entry.Mode))
                        return ExceptionHandlingLevel.Ignore;

            return level;
        }

        ExceptionHandlingLevel? IExceptionFilter.GetLevel(ExceptionPropertyCollection properties, Exception exception) {
            return HandleExceptionCore(properties);
        }

        ExceptionHandlingLevel? IExceptionFilter.GetLevel(ExceptionPropertyCollection properties, string content) {
            return HandleExceptionCore(properties);
        }
    }
}